/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.xibit.jsimpleportforward;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author David
 */
public class ForwardThread extends Thread {

	private final Forward forward;
	private boolean stopped = false;
	private ServerSocket ss;

	public ForwardThread(Forward forward) {
		super("TForward:" + forward.getFromPort() + "->" + forward.getToPort());
		this.forward = forward;
	}

	@Override
	public void run() {
		System.out.println("Forward thread started.");
		try {
			ss = new ServerSocket(forward.getFromPort());
			while (!stopped) {
				Socket sourceSocket = ss.accept();
				System.out.println("Connection accepted on port:" + forward.getFromPort());
				try {
					new CommThread(sourceSocket, forward.getToPort()).start();
				} catch (IOException ex) {
					Logger.getLogger(ForwardThread.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
		} catch (IOException ex) {
			Logger.getLogger(ForwardThread.class.getName()).log(Level.SEVERE, null, ex);
		} catch (Throwable t) {
		} finally {
			stopped = true;
			if (ss != null) {
				try {
					ss.close();
				} catch (IOException ex) {
					// who cares
				}
			}
			System.out.println("Forward thread stopped.");
		}
	}
	
	public void stopThisForward() {
		this.stopped = true;
		this.interrupt();
		ServerSocket tmpSs = ss;
		ss = null;
		if (tmpSs != null) {
			try {
				tmpSs.close();
			} catch (IOException ex) {
				// who cares
			}
		}
//		try {
//			ss.close();
//		} catch (IOException ex) {
//			//Logger.getLogger(ForwardThread.class.getName()).log(Level.SEVERE, null, ex);
//		}
//		ss = null;
	}

	public Forward getForward() {
		return forward;
	}
}
